//  this library.
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:hktk_app/dao/course_dao.dart';
import 'package:hktk_app/dao/download_dao.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/subject/add_frequency_type.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/page_title_widget.dart';
import 'package:hktk_app/widget/subject/preview_mask_widget.dart';
import 'package:photo_view/photo_view.dart';

/// 图片预览
class ImagePreviewPage extends StatefulWidget {
  /// 资源文件路径
  final String url;

  /// 资源文件名称
  final String name;

  /// 资源文化类型
  final String type;

  /// 是否显示预览提示
  final bool showTips;

  /// 当预览模式不显示时可以为空
  final String columnId;

  /// 是否是网络文件
  final bool netWork;

  /// 资料相关id
  final String resId;

  /// 是否是视频相关的资料。true：是，false：不是。默认false
  /// 控制添加观看次数方法，只有重网络查看时才添加次数，否则不添加
  final bool videoRes;

  const ImagePreviewPage({
    super.key,
    required this.url,
    required this.name,
    required this.type,
    this.showTips = false,
    this.columnId = "",
    this.netWork = true,
    this.resId = "",
    this.videoRes = false,
  });

  @override
  State<ImagePreviewPage> createState() => _ImagePreviewPageState();
}

class _ImagePreviewPageState extends State<ImagePreviewPage> {
  late BuildContext _context;

  /// 加载相关数据
  late Future<Map<String, dynamic>> _futureInit;

  @override
  void initState() {
    super.initState();
    debugPrint("imagePreviewPage 页面 -> initState 方法执行 ===> ");
    debugPrint("");
    _futureInit = _initData();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("imagePreviewPage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    _context = context;
    return Scaffold(
      backgroundColor: colorWhite2,
      body: Column(
        children: [
          PageTitleWidget(
            name: widget.name,
            pageContext: context,
            rightShow: widget.netWork,
            rightChild: downloadBtn(),
            rightFun: _onTapFunRight,
          ),
          Expanded(
            child: _futureItem(),
          ),
        ],
      ),
    );
  }

  /// 加载方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      if (widget.netWork) {
        if (!widget.videoRes) {
          // 增加查看次数
          await SubjectDao.addFrequency(
            type: AddFrequencyType.watch_time,
            id: widget.resId,
          );
        } else {
          // 增加查看次数（视频）
          await CourseDao.addFrequency(
            resId: widget.resId,
          );
        }
      }
      map["suc"] = true;
    } catch (e) {
      debugPrint("imagePreviewPage 页面 -> 初始化方法发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("imagePreviewPage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// future异步执行方法
  _futureItem() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
          ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: _context, msg: map["msg"]);
            });
          }
          return _stackContent();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 内容显示
  _stackContent() {
    return Stack(
      children: [
        Positioned.fill(child: _content()),
        if (widget.showTips)
          PreviewMaskWidget(
            columnId: widget.columnId,
          ),
      ],
    );
  }

  /// 内容显示方法
  _content() {
    ImageProvider image;
    if (widget.netWork) {
      image = NetworkImage(widget.url);
    } else {
      image = FileImage(File(widget.url));
    }
    return PhotoView(
      imageProvider: image,
    );
  }

  /// 点击方法
  _onTapFunRight() {
    debugPrint("imagePreviewPage 页面 -> 你点击了下载 ===> ${widget.showTips}");
    // 提示
    ToastUtil.show(context: _context, msg: "开始下载");
    // 开始下载
    _futureDownload().then((Map<String, dynamic> map) {
      ToastUtil.show(context: _context, msg: map["msg"]);
    });
  }

  /// 下载方法执行
  Future<Map<String, dynamic>> _futureDownload() async {
    Map<String, dynamic> map = {};
    try {
      if (!widget.videoRes) {
        // 增加下载次数
        await SubjectDao.addFrequency(
          type: AddFrequencyType.download_time,
          id: widget.resId,
        );
      }

      // 开始下载
      DataModel dataModel = dataUtilComm.dataModel;
      bool suc = await DownloadDao.downloadFile(
        url: widget.url,
        dataModel: dataModel,
        name: widget.name,
        type: widget.type,
      );
      map["suc"] = suc;
      map["msg"] = suc ? "下载成功" : "下载失败";
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }
}
